package com.spring.cold.security;

import com.spring.cold.pojo.User;
import com.spring.cold.pojo.UserRole;
import com.spring.cold.service.UserRoleService;
import com.spring.cold.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        User user = userService.selectByLoginName(loginName);
        if (user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<UserRole> userRoles = userRoleService.selectByUserId(user.getId());
        for (UserRole userRole : userRoles) {
            authorities.add(new SimpleGrantedAuthority(userRole.getName()));
        }
        return new CustomizeUser(user.getId(),user.getName(),user.getIsAdmin(),user.getLoginName(),user.getPassword(),authorities);
    }
}
